<?php
namespace Admin_\Controller;
use Think\Controller;
class UserController extends Controller {
    public function __construct()
    {
        parent::__construct();
        $this->_login = A('Login');
        //判断是否登录
        if(!$this->_login->check_login()){
            $this->_login->to_login();die;
        }
    }

    /**
     * 查看记录列表
     */
    public function index(){
        $info_list = M('user')->where(array(
            'is_delete' => 0,
        ))->select();

        $this->assign('info_list',$info_list);
    $this->display();
    }


    /**
     * 添加一条记录
     */
    public function add(){
        if(IS_POST){
            if(!I('post.name'))
                JSON(array('code'=>201,'message'=>'用户名不能为空'));
            if(!$passwd = I('post.passwd'))
                JSON(array('code'=>203,'message'=>'密码不能为空'));
            $_POST['passwd'] = $this->_login->make_sign($passwd);
            $_POST['create_time'] = time();
            $_POST['header_img'] = time();
            $_POST['last_time'] = time();
            if(D('user')->create() && D('user')->add()){
                JSON(array('code'=>200,'message'=>'添加成功','data'=>array('go_url'=>U('User/index'))));
            }
            JSON(array('code'=>207,'message'=>'添加失败'));
        }
        $this->display();
    }

    /**
     * 修改一条记录
     */
    public function edit(){
        $id = I('get.id')+0;
        if($id){
            if(IS_POST){
                if(!I('post.name'))
                    JSON(array('code'=>201,'message'=>'用户名不能为空'));
                if(!$passwd = I('post.passwd'))
                    JSON(array('code'=>203,'message'=>'密码不能为空'));
                $_POST['passwd'] = $this->_login->make_sign($passwd);
                $_POST['id'] = $id;
                if(D('user')->create() && D('user')->save()){
                    JSON(array('code'=>300,'message'=>'修改成功','data'=>array('go_url'=>U('User/index'))));
                }
                JSON(array('code'=>307,'message'=>'修改失败'));
            }
            $info = M('user')->where(array(
                'is_delete' => 0,
                'id' => $id,
            ))->find();
            if(!$info)
                header('Location: '.U('User/index'));
            $this->assign('info',$info);
            $this->display();
        }
    }

    public function del(){
        $id = I('get.id')+0;
        if($id){
            $del_res = M('user')->where(array('id'=>$id))->setField('is_delete',1);
            if($del_res)
                JSON(array('code'=>400,'message'=>'删除成功'));
        }
        JSON(array('code'=>401,'message'=>'删除失败'));
    }

}
